#include "KPF_Socket.h"

KPF_Socket::KPF_Socket( void )
	: pm_Socket(NULL)
{
	
}

KPF_Socket::KPF_Socket( C_SOCKET_TYPE eType )
	: pm_Socket(NULL)
{
	switch ( eType )
	{
	case KPF_SOCKET_TYPE_UDP:
	{
		pm_Socket = net_socket( SOCKET_TYPE_DGRAM, 0 );
	}break ;
	case KPF_SOCKET_TYPE_TCP:
	{
		pm_Socket = net_socket( SOCKET_TYPE_STREAM, 0 );
	}break ;
	case KPF_SOCKET_TYPE_MULTICAST:
	{
		pm_Socket = net_socket( SOCKET_TYPE_MULTICAST, 0 );
	}break ;
	default:
	{
		
	}break ;	
	}
}

KPF_Socket::~KPF_Socket( void )
{
	if ( pm_Socket )
	{
		net_close_socket( (CSocket *)pm_Socket );
		pm_Socket = NULL;
	}
}

KPF_Socket::KPF_Socket( CSocket *pSocket )
{
	pm_Socket = pSocket;
}

KPF_Socket &KPF_Socket::operator =( const KPF_Socket &other )
{
	if ( this != &other )
	{
		this->pm_Socket = other.pm_Socket;
	}

	return *this;
}
	
int32_t KPF_Socket::Send( const int8u_t *pData, const int32_t iDataLen )
{
	int32_t iRetCode = -1;
	
	iRetCode = net_send( pm_Socket, pData, iDataLen );
	
	return iRetCode;
}

int32_t KPF_Socket::Recv( int8u_t *pDataBuf, const int32_t iDataBufLen )
{
	int32_t iRetCode = -1;
	
	if ( pDataBuf && iDataBufLen > 0 )
		iRetCode = net_recv( pm_Socket, pDataBuf, iDataBufLen );	
	
	return iRetCode;
}
	
int32_t KPF_Socket::Sendto( const int8u_t *pData, const int32_t iDataLen, KPF_Addr *pAddr )
{
	int32_t iRetCode = -1;
	
	CNetAddr *pNetAddr = NULL;
	
	if ( pAddr )
	{
		
		pNetAddr = pAddr->getAddr(  );
	}

	iRetCode = net_sendto( pm_Socket, pData, iDataLen, pNetAddr );	
	
	return iRetCode;
}
int32_t KPF_Socket::Recvfrom( int8u_t *pDataBuf, const int32_t iDataBufLen, KPF_Addr *pAddr )
{
	int32_t iRetCode = -1;
	
	CNetAddr *pNetAddr = NULL;
	
	if ( pAddr )
	{
		
		pNetAddr = pAddr->getAddr(  );
	}
	
	iRetCode = net_recvfrom( pm_Socket, pDataBuf, iDataBufLen, pNetAddr );
	
	return iRetCode;
}

void KPF_Socket::setSocket( const CSocket *pSocket )
{
	pm_Socket = pSocket;
}

const CSocket *KPF_Socket::getSocket( void )
{
	return pm_Socket;
}

